package com.trade.okxserver.operator;

import com.ql.util.express.Operator;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class VarianceOperator extends Operator {
    @Override
    public BigDecimal executeInner(Object[] objects) throws Exception {
        // 计算平均值
        BigDecimal total = BigDecimal.ZERO;
        for (Object object : objects) {
            total = total.add(new BigDecimal(object.toString()));
        }
        BigDecimal avg = total.divide(new BigDecimal(objects.length), 4, RoundingMode.HALF_DOWN);

        BigDecimal variance = BigDecimal.ZERO;
        for (Object object : objects) {
            BigDecimal decimal = new BigDecimal(object.toString()).subtract(avg);
            variance = variance .add(decimal.multiply(decimal));
        }

        return variance.divide(new BigDecimal(objects.length), 4, RoundingMode.HALF_DOWN);
    }
}
